<template>
  <div class="direct-feedback-example">
    <div class="example-header">
      <h2 class="text-2xl font-bold text-gray-800 mb-4">直接反馈系统示例</h2>
      <p class="text-gray-600 mb-6">
        演示新的直接反馈功能：点击点赞/踩一踩按钮直接调用 updateFeedback 接口
      </p>
    </div>

    <!-- 控制面板 -->
    <div class="control-panel">
      <h3 class="text-lg font-semibold mb-3">测试控制</h3>
      <div class="control-buttons">
        <button @click="addAIMessage" class="btn btn-primary">
          添加AI消息
        </button>
        <button @click="clearMessages" class="btn btn-secondary">
          清空消息
        </button>
        <button @click="toggleMockError" class="btn" :class="mockError ? 'btn-danger' : 'btn-success'">
          {{ mockError ? '关闭' : '开启' }}模拟错误
        </button>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-area">
      <div v-if="messages.length === 0" class="empty-state">
        <p class="text-gray-500 text-center py-8">
          点击"添加AI消息"开始测试反馈功能
        </p>
      </div>
      
      <ChatMessage
        v-for="message in messages"
        :key="message.id"
        :message="message"
        :feedback-disabled="false"
        @feedback="handleDirectFeedback"
      />
    </div>

    <!-- 反馈日志 -->
    <div class="feedback-log">
      <h3 class="text-lg font-semibold mb-3">反馈日志</h3>
      <div class="log-content">
        <div v-if="feedbackLogs.length === 0" class="text-gray-500 text-sm">
          暂无反馈记录
        </div>
        <div 
          v-for="(log, index) in feedbackLogs" 
          :key="index"
          class="log-item"
          :class="log.success ? 'log-success' : 'log-error'"
        >
          <span class="log-time">{{ formatTime(log.timestamp) }}</span>
          <span class="log-message">{{ log.message }}</span>
          <span class="log-status" :class="log.success ? 'text-green-600' : 'text-red-600'">
            {{ log.success ? '✓' : '✗' }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import ChatMessage from '@/components/chat/ChatMessage.vue'
import type { ChatItem, Feedbacktype } from '@/types/app'

// 状态管理
const messages = ref<ChatItem[]>([])
const feedbackLogs = ref<Array<{
  timestamp: number
  message: string
  success: boolean
}>>([])
const mockError = ref(false)

// 生成唯一ID
const generateId = () => `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

// 添加AI消息
const addAIMessage = () => {
  const aiResponses = [
    "这是一个测试AI回复，请尝试点击下方的点赞或踩一踩按钮来测试直接反馈功能。",
    "我是AI助手，正在为您提供帮助。您可以通过反馈按钮告诉我这个回答是否有用。",
    "直接反馈系统让用户体验更加流畅，无需填写额外的表单即可提交反馈。"
  ]
  
  const randomResponse = aiResponses[Math.floor(Math.random() * aiResponses.length)]
  
  const message: ChatItem = {
    id: generateId(),
    content: randomResponse,
    isAnswer: true,
    message_files: [],
    agent_thoughts: [],
    feedback: undefined
  }
  
  messages.value.push(message)
  addFeedbackLog(`添加了新的AI消息: ${message.id}`, true)
}

// 清空消息
const clearMessages = () => {
  messages.value = []
  addFeedbackLog('清空了所有消息', true)
}

// 切换模拟错误
const toggleMockError = () => {
  mockError.value = !mockError.value
  addFeedbackLog(`${mockError.value ? '开启' : '关闭'}了模拟错误模式`, true)
}

// 模拟updateFeedback接口调用
const mockUpdateFeedback = async (messageId: string, feedback: Feedbacktype): Promise<void> => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  if (mockError.value) {
    throw new Error('模拟的网络错误')
  }
  
  // 模拟成功响应
  console.log('模拟updateFeedback调用成功:', { messageId, feedback })
}

// 处理直接反馈
const handleDirectFeedback = async (messageId: string, feedback: Feedbacktype) => {
  addFeedbackLog(`开始提交反馈: ${feedback.rating} (消息ID: ${messageId})`, true)
  
  try {
    // 调用模拟的updateFeedback接口
    await mockUpdateFeedback(messageId, feedback)
    
    // 更新本地消息状态
    const message = messages.value.find(m => m.id === messageId)
    if (message) {
      message.feedback = feedback
    }
    
    addFeedbackLog(`反馈提交成功: ${feedback.rating}`, true)
  } catch (error: any) {
    console.error('反馈提交失败:', error)
    addFeedbackLog(`反馈提交失败: ${error.message}`, false)
    
    // 可以在这里添加用户友好的错误提示
    // 例如显示Toast通知
  }
}

// 添加反馈日志
const addFeedbackLog = (message: string, success: boolean) => {
  feedbackLogs.value.unshift({
    timestamp: Date.now(),
    message,
    success
  })
  
  // 限制日志数量
  if (feedbackLogs.value.length > 20) {
    feedbackLogs.value = feedbackLogs.value.slice(0, 20)
  }
}

// 格式化时间
const formatTime = (timestamp: number): string => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.direct-feedback-example {
  @apply max-w-4xl mx-auto p-6 space-y-6;
}

.example-header {
  @apply text-center;
}

.control-panel {
  @apply bg-white p-4 rounded-lg border border-gray-200 shadow-sm;
}

.control-buttons {
  @apply flex flex-wrap gap-2;
}

.btn {
  @apply px-4 py-2 rounded-lg font-medium transition-colors;
}

.btn-primary {
  @apply bg-blue-500 text-white hover:bg-blue-600;
}

.btn-secondary {
  @apply bg-gray-500 text-white hover:bg-gray-600;
}

.btn-success {
  @apply bg-green-500 text-white hover:bg-green-600;
}

.btn-danger {
  @apply bg-red-500 text-white hover:bg-red-600;
}

.chat-area {
  @apply bg-white rounded-lg border border-gray-200 shadow-sm min-h-48;
}

.empty-state {
  @apply p-8;
}

.feedback-log {
  @apply bg-gray-50 p-4 rounded-lg border border-gray-200;
}

.log-content {
  @apply max-h-48 overflow-y-auto space-y-1;
}

.log-item {
  @apply flex items-center justify-between text-sm py-2 px-3 rounded;
}

.log-success {
  @apply bg-green-50 border border-green-200;
}

.log-error {
  @apply bg-red-50 border border-red-200;
}

.log-time {
  @apply text-gray-500 font-mono text-xs;
}

.log-message {
  @apply flex-1 mx-3 text-gray-700;
}

.log-status {
  @apply font-bold;
}
</style> 